import { createRouter, createWebHashHistory } from "vue-router";
import store from "@/store"
import nProgress from "nprogress";
// 定义路由匹配规则
const routes = [
  {
    path: "/home",
    name:'admin',
    component: () => import("@/views/home.vue"),
    children:[
      {
        path:'/home',
        name:'/home',
        component:() => import("@/views/HomeIndex.vue"),
        meta:{
          title:'首页'
        }
      },
      {
        path:'/image/list',
        name:'imageList',
        component:() => import("@/views/PicList.vue"),
        meta:{
          title:'图库管理'
        }
      },
      {
        path:'/manager/list',
        name:'managerList',
        component:() => import("@/views/Manager.vue"),
        meta:{
          title:'管理员管理'
        }
      },
      {
        path:'/access/list',
        name:'accessList',
        component:() => import("@/views/Rules.vue"),
        meta:{
          title:'权限管理'
        }
      },
      {
        path:'/role/list',
        name:'RoleList',
        component:() => import("@/views/Roles.vue"),
        meta:{
          title:'角色管理'
        }
      },
      {
        path:'/user/list',
        name:'UserList',
        component:() => import("@/views/User.vue"),
        meta:{
          title:'用户管理'
        }
      },
      {
        path:'/skus/list',
        name:'SkuList',
        component:() => import("@/views/Sku.vue"),
        meta:{
          title:'规格管理'
        }
      },
      {
        path:'/goods/list',
        name:'GoodList',
        component:() => import("@/views/GoodsList.vue"),
        meta:{
          title:'商品管理'
        }
      },

    ]
  },
  {
    path: "/login",
    component: () => import("@/views/login.vue"),
  },
  {
    path: "/:pathMatch(.*)",
    name: "NotFound",
    component: () => import("@/views/404.vue"),
  },
];
// 创建路由实例对象
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
// 全局路由守卫
router.beforeEach(async(to, from, next) => {
    nProgress.start()
  // 获取token
  const tokenStr = window.sessionStorage.getItem("token");
  if(tokenStr) {
    await store.dispatch('getUserInfo')
  }
  // 如果未登录跳转到登录页面
  if (!tokenStr && to.path !== "/login") return next("/login");
  // 如果已经登录，则禁止返回登录页面
  if (tokenStr && to.path == "/login") {
    return next({ path: from.path ? from.path : "/" });
  }
  next()
});
// 全局路由后置守卫
router.afterEach((to,from) => {
    nProgress.done()
})
// 共享路由实例对象
export default router;
